package org.zoomdev.zoom.dao.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.configs.Insert;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.modules.CoreDaoModule;
import org.zoomdev.zoom.dao.utils.LogUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertExecutor implements SqlExecutor {

    private static final Logger log = LoggerFactory.getLogger(CoreDaoModule.NAME);

    public int execute(SqlConfig cfg, Object data) {
        if (data == null) {
            throw new NullPointerException();
        }
        Insert insert = cfg.getInsert();
        Entity entity = cfg.getEntity();
        insert.prepare(cfg, entity, data, cfg.isIgnoreNull());
        String sql = insert.buildSql(cfg);
        if (CoreDaoModule.logSql) {
            log.info(LogUtils.getSql(sql, insert.getValues()));
        }
        try {
            Connection conn = cfg.openConnection();
            try (PreparedStatement stmt = entity.prepareInsert(conn, sql)) {
                insert.setParameter(stmt, 1);
                int ret = stmt.executeUpdate();
                if (ret > 0) {
                    entity.afterInsert(cfg, data, stmt);
                }
                return ret;
            }
        } catch (SQLException e) {
            throw new DaoException("执行insert失败:" + LogUtils.getSql(sql, insert.getValues()), e);
        }
    }


}
